﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System.Text.RegularExpressions;
using BIZ;

namespace JoyLibrary.Controllers
{
    public class SearchController : Controller
    {
        //
        // GET: /Search/
        BIZ.BookOper bOper = new BIZ.BookOper();
        BIZ.UserOper uo = new BIZ.UserOper();
        LibraryBookIndentOper indentOper = new LibraryBookIndentOper(); 
        BIZ.BorrowBooksRule bookRule = new BIZ.BorrowBooksRule();


        public ActionResult list()
        {
            int e = Request["e"] == null ? -1 : int.Parse(Request["e"].ToString());//lb_ebook电子或图书
            int l = Request["l"] == null ? -1 : int.Parse(Request["l"].ToString());//lb_language语种
            int z = Request["z"] == null ? -1 : int.Parse(Request["z"].ToString());//lb_bookTheme主题
            int le = Request["le"] == null ? -1 : int.Parse(Request["le"].ToString());//lb_level级别
            int y = Request["y"] == null ? -1 : int.Parse(Request["y"].ToString());//lb_forAge适读年龄
            int x = Request["x"] == null ? -1 : int.Parse(Request["x"].ToString());//lb_bookType类型
            int cd = Request["cd"] == null ? -1 : int.Parse(Request["cd"].ToString());//cd
            int mp3 = Request["mp3"] == null ? -1 : int.Parse(Request["mp3"].ToString());//mp3
            int inventory = Request["inventory"] == null ? -1 : int.Parse(Request["inventory"].ToString());//库存
            string tt = Request["tt"] == null ? "" : Server.HtmlDecode(Request["tt"].ToString());//查询文字
            int pageno = Request["pageno"] == null ? 1 : int.Parse(Request["pageno"].ToString());//当前页
            int pagesite = 15;
            IList list = bOper.getBookist(tt, l, e, y, le, x, z, cd, mp3, inventory, pageno, pagesite);
            ViewData["booklist"] = list;
            return View();
        }

        public ActionResult detail(string id)
        {
            IList li = bOper.getLibraryBookbyid(Regex.Match(id, "^\\d+$").Success ?int.Parse(id) : 0);
            if (li.Count <= 0) return RedirectToAction("noBook", "search");//如果图书不存在
            ViewData["bookinfo"] = li;
            return View();
        }

        public ActionResult libraryCar()
        {
            IList list=(IList)Session["car"];
            ViewData["booklist"] = list;
            return View();
        }

        public string saveUserSave()
        {
            DomainModel.UserInfo user = (DomainModel.UserInfo)Session["user"];       
            int dlid = Request["dlid"] == null ? -1 : int.Parse(Request["dlid"].ToString());
            int lbid = Request["lbid"] == null ? -1 : int.Parse(Request["lbid"].ToString());
            bool falg = uo.checkUserSave(lbid, user.u_id);
            if (falg)
                return "have";
            uo.saveUserSave(dlid, lbid);
            return "y";
        }

        public string addLibrary()
        {
            if (Session["car"] == null)
            {
                IList list1 = new ArrayList();
                Session["car"] = list1;
            }
            string lb_id = Request.Form["lb_id"];
            string lb_bookName = Request.Form["lb_bookName"];
            string lb_translatedName = Request.Form["lb_translatedName"];
            string lb_forAge = Request.Form["lb_forAge"];
            string lb_price = Request.Form["lb_price"];
            string lb_level = Request.Form["lb_level"];
            string lb_cover = Request.Form["lb_cover"];
            IList list = (IList)Session["car"];
            Hashtable tb = new Hashtable();
            tb.Add("lb_id", lb_id);
            tb.Add("lb_bookName", lb_bookName);
            tb.Add("lb_translatedName", lb_translatedName);
            tb.Add("lb_forAge", lb_forAge);
            tb.Add("lb_price", lb_price);
            tb.Add("lb_level", lb_level);
            tb.Add("lb_cover", lb_cover);
            if (list.Count > 0)
            {
                foreach (Hashtable t in list)
                {
                    if (t.ContainsValue(lb_id))
                    {
                        return "have";//已经有这本书了
                    }
                }
                //if (((Hashtable)list[0]).ContainsValue(lb_id))//已经有这本书了
                //    return "have";
            }
            list.Add(tb);
            Session["car"] = list;
            return "y";
        }

        public string delLibrary()
        {
            string lb_id = Request.Form["lb_id"];
            IList list = (IList)Session["car"];
            foreach (Hashtable tb in list)
            {
                if (tb["lb_id"].ToString() == lb_id)
                {
                    list.Remove(tb);
                    break;
                    //return "y";
                }
            }
            
            Session["car"] = list;
            return "y";
        }

        public string saveLibraryBookIndent()
        {
            DomainModel.UserInfo user = (DomainModel.UserInfo)Session["user"];            
            //DomainModel.LibraryBookIndent _staff = new DomainModel.LibraryBookIndent();            
            //string bookname = Request.Form["bookname"];
            string lbid = Request.Form["lbid"];
            string[] arr = lbid.Split(',');//借几本书
            string str = bookRule.validationUser(user.u_id, arr.Length);
            if (str == "best4")
                return "best4";//最多4本
            else if (str == "notimes")
                return "notimes";//无剩余次数
            else if (str == "nocard")
                return "nocard";
            else if (str == "erroruserrule")
                return "erroruserrule";
            else if (str == "erroruser")
                return "erroruser";
            //erroruserrule
            else if (str.StartsWith("good"))
            {
                for (int i = 0; i < arr.Length; i++)
                {
                    int f = bookRule.validationBooks(int.Parse(arr[i].ToString()));
                    if (f == 2)
                        return "bdzs";//电子书不能进入订单流程
                    else if (f == 0)
                        return "bbcz";//图书不存在
                    else if (f == 1)
                        return "bnkc";//没有库存
                    else if (f == 4)//图书为下架或删除状态
                        return "bxj";
                }
                string[] arr1 = str.Split(',');
                IList list = indentOper.indent(lbid, System.Web.HttpContext.Current.Request.UserHostAddress, arr1[1].ToString(), user.u_id);
                Hashtable hs = (Hashtable)list[0];
                if (hs["returns"].ToString() == "succe")
                {
                    Session.Remove("car");//清空借书车的session
                    return "succe";
                }
                else
                {
                    return hs["returns"].ToString().Substring(5, hs["returns"].ToString().Length);
                    //lose:徐测试第二,地图,徐测试
                }
                //_staff.lbi_ucid = int.Parse(arr1[1].ToString());
                //_staff.lbi_ip = System.Web.HttpContext.Current.Request.UserHostAddress;
                //_staff.lbi_time = DateTime.Now;
                //_staff.lbi_uid = user.u_id;
                //_staff.lbi_state = (int)DAL.Enums.lbistate.处理中;
                //bOper.save(_staff);
                //添加订单
            }
            else
                return "";
            #region 
            //for (int i = 0; i < arr.Length; i++)
            //{
            //    IList list = bOper.getBookIdIsbn(arr[i].ToString());
            //    int bookid = int.Parse(((Hashtable)list[0])["lb_id"].ToString());
            //    string isbn = ((Hashtable)list[0])["lbd_isbn"].ToString();
            //    int bookdetailid = int.Parse(((Hashtable)list[0])["lbd_id"].ToString());//
            //    bOper.subtractInventOry(bookid);//修改图书库存
            //    bOper.updateIsbnBookState(bookdetailid, (int)DAL.Enums.isbnstate.借出);//根据图书id和isbn号修改图书明细表图书借出状态

            //    int f = bookRule.validationBooks(bookid);
            //    if (f == 2)
            //        return "bdzs";//电子书不能进入订单流程
            //    else if (f == 0)
            //        return "bbcz";//图书不存在
            //    else if (f == 1)
            //        return "bnkc";//没有库存
            //    else if (f == 4)//图书为下架或删除状态
            //        return "bxj";
            //    bOper.saveIndentDetail(_staff.lbi_id, bookdetailid);//订单明细表添加明细
            //}
            //bOper.saveIndentLog(_staff.lbi_id, 0, _staff.lbi_state, ((DomainModel.cmsuser)Session["cmsuser"]).id);//添加订单变更记录（一条）
            //return "y";
            #endregion 
        }
    }
}
